/**
 * Created by ptt on 2016/6/8/0008.
 */
define(["./TP.js"], function (TP) {
    var tpl = TP.tpl;
    var Controller = {};
    Controller.create = function (includes) {
        var result = function () {
            this.init.apply(this, arguments);
        };
        result.fn = result.prototype;
        result.fn.init = function (element) {
            this.el = jQuery(element);
            this.refreshElements();
            this.delegateEvents();
            this.jrt();
        };
        result.include = function (ob) {$.extend(this.fn, ob); };
        result.extend = function(ob) {$.extend(this, ob);};
        result.fn.proxy = function (func) {
            return jQuery.proxy(func, this);
        };
        result.fn.refreshElements = function () {
            for (var key in this.elements) {
                if (this.elements.hasOwnProperty(key)) {
                    this[this.elements[key]] = jQuery(key, this.el);
                }
            }
        };
        result.fn.jrt = function () {

        };
        result.fn.trigger = function (elem, eventType) {
            this[elem].trigger(eventType);
        };
        result.fn.render = function (data) {
            var template = this.template;
            $(template).length > 0 &&
            this.el.html(template === "" ? $("<div>") :
               tpl($(template).html().replace(/[\n\r\t]+/g, "")).render(data));
            this.refreshElements();
        };
        result.fn.eventSplitter = /^(\w+)\s*(.*)$/;
        result.fn.delegateEvents = function () {
            for (var key in this.events) {
                if (this.events.hasOwnProperty(key)) {
                    var methodName = this.events[key];
                    var method = this.proxy(this[methodName]);
                    var match = key.match(this.eventSplitter);
                    var eventName = match[1];
                    var selector = match[2];
                    selector === "" ? this.el.on(eventName, method) : this.el.on(eventName, selector, method);
                }
            }
        };
        result.fn.elements = {};
        result.fn.events = {};
        result.fn.template = "";
        includes && result.include(includes);
        return result;
    };
    return {
        Controller: Controller
    }
});